import axios from "axios";
import { Loading } from "element-ui";

const { getSetting } = window.systemParamsUtils;

let loadingMap = {};
let loadingShow = function(config) {
    if (!config["loading"]) {
        return;
    }
    let loading = Loading.service({
        lock: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.8)",
        text: config["loadingText"] || "数据加载中..."
    });
    config.uuid = new Date().getTime() + "=" + config.url;
    loadingMap[config.uuid] = loading;
};
let loadingHide = function(config) {
    if (!config["loading"]) {
        return;
    }
    loadingMap[config.uuid] && loadingMap[config.uuid].close();
    delete loadingMap[config.uuid];
};
// create an axios instance
const service = axios.create({
    baseURL: getSetting("BASE_API"), // api 的 base_url
    timeout: getSetting("REQ_TIMEOUT") || 5000 // request timeout
});

// request interceptor
service.interceptors.request.use(
    config => {
        // Do something before request is sent
        config = window.loginUtil.beforeRequest(config);
        config.headers["X-Requested-With"] = "XMLHttpRequest";
        loadingShow(config);

        return config;
    },
    error => {
        // Do something with request error
        console.log(error); // for debug
        Promise.reject(error);
    }
);

// response interceptor
service.interceptors.response.use(
    response => {
        loadingHide(response.config);
        response = window.loginUtil.afterResponseSuccess(response);
        return response;
    },
    error => {
        window.loginUtil.afterResponseFailed(error);
        if (error && error.config) {
            loadingHide(error.config);
        }
        console.log("err" + error); // for debug
        return Promise.reject(error);
    }
);

export default service;
